﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model.ParInfo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace AchieveManageWeb.Controllers
{
    public class ProInfoController : Controller
    {
        //
        // GET: /ProInfo/

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult ProAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加项目信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ProInfoAdd(ProInfoModel pim)
        {
            string newID = Guid.NewGuid().ToString();
            ProInfo_Tab pit = new ProInfo_Tab();
            pit.ProjectGuid = newID;
            pit.ProjectId = pim.ProjectId;
            pit.ProjectName = pim.ProjectName;
            pit.ProjectManager = pim.ProjectManager;
            pit.ProjectTel = pim.ProjectTel;
            pit.SignTime = pim.SignTime;
            pit.CompletionTime = pim.CompletionTime;
            pit.AcceptanceTime = pim.AcceptanceTime;
            pit.WarrantyTime = pim.WarrantyTime;
            pit.UserManager = pim.UserManager;
            pit.UserTel = pim.UserTel;
            pit.Describe = pim.Describe;
            pit.Address = pim.Address;
            pit.Longitude = pim.Longitude;
            pit.Latitude = pim.Latitude;
            pit.AddTime = System.DateTime.Now;
            int code = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                int tmpCount = Entities.ProInfo_Tab.Where(i => i.ProjectId == pim.ProjectId).Count();
                if (tmpCount > 0)
                {
                    return Content("{\"msg\":\"添加失败！项目编号已存在！\",\"success\":false}");
                }
                Entities.ProInfo_Tab.Add(pit);
                Entities.Entry<ProInfo_Tab>(pit).State = System.Data.Entity.EntityState.Added;
                code = Entities.SaveChanges();
            }
            if (code > 0)
            {
                return Content("{\"msg\":\"添加成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"添加失败！入库失败\",\"success\":false}");
            }
        }

        /// <summary>
        /// 项目编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult ProEdit()
        {
            ProInfoModel lin = new ProInfoModel();
            string ProjectGuid = Request["ProjectGuid"];

            using (CYOADBEntities Entities = new CYOADBEntities())
            {

                var linqs = from a in Entities.ProInfo_Tab.Where(i => i.ProjectGuid == ProjectGuid)
                            select new ProInfoModel
                            {
                                ProjectGuid = a.ProjectGuid,
                                ProjectId = a.ProjectId,
                                ProjectName = a.ProjectName,
                                ProjectManager = a.ProjectManager,
                                ProjectTel = a.ProjectTel,
                                SignTime = a.SignTime,
                                CompletionTime = a.CompletionTime,
                                AcceptanceTime = a.AcceptanceTime,
                                WarrantyTime = a.WarrantyTime,
                                UserManager = a.UserManager,
                                UserTel = a.UserTel,
                                Describe = a.Describe,
                                Address = a.Address,
                                Longitude = a.Longitude,
                                Latitude = a.Latitude,
                            };
                lin = linqs.FirstOrDefault();
            };

            return View(lin);
        }

        /// <summary>
        /// 编辑基站信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ProInfoEdit(ProInfoModel pim)
        {
            try
            {
                int code = 0;
                using (CYOADBEntities Entities = new CYOADBEntities())
                {


                    ProInfo_Tab pit = Entities.ProInfo_Tab.Where(i => i.ProjectGuid == pim.ProjectGuid).FirstOrDefault();
                    if (pit == null)
                    {
                        return Content("{\"msg\":\"修改失败！未查询到此项目\",\"success\":false}");
                    }
                    pit.ProjectId = pim.ProjectId;
                    pit.ProjectName = pim.ProjectName;
                    pit.ProjectManager = pim.ProjectManager;
                    pit.ProjectTel = pim.ProjectTel;
                    pit.SignTime = pim.SignTime;
                    pit.CompletionTime = pim.CompletionTime;
                    pit.AcceptanceTime = pim.AcceptanceTime;
                    pit.WarrantyTime = pim.WarrantyTime;
                    pit.UserManager = pim.UserManager;
                    pit.UserTel = pim.UserTel;
                    pit.Describe = pim.Describe;
                    pit.Address = pim.Address;
                    pit.Longitude = pim.Longitude;
                    pit.Latitude = pim.Latitude;
                    pit.AddTime = System.DateTime.Now;


                    Entities.ProInfo_Tab.Add(pit);
                    Entities.Entry<ProInfo_Tab>(pit).State = System.Data.Entity.EntityState.Modified;
                    code = Entities.SaveChanges();
                };
                if (code > 0)
                {

                    return Content("{\"msg\":\"修改成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"修改失败！入库失败\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"修改失败," + ex.Message + "\",\"success\":false}");
            }
        }

        /// <summary>
        /// 根据条件获取项目信息
        /// </summary>
        public ActionResult GetAllProInfo()
        {
            try
            {

                //首先获取前台传递过来的参数
                int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
                int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);
                DateTime tmp = DateTime.ParseExact("19000101", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                string selProjectName = Request["selProjectName"] == null ? "" : Request["selProjectName"].ToString();
                string selProjectId = Request["selProjectId"] == null ? "" : Request["selProjectId"].ToString();
                DateTime selStartWarrantyTime = Request["selStartWarrantyTime"] == null|| Request["selStartWarrantyTime"] == "" ? tmp : DateTime.Parse(Request["selStartWarrantyTime"].ToString());
                DateTime selEndWarrantyTime = Request["selEndWarrantyTime"] == null || Request["selEndWarrantyTime"] == "" ? tmp : DateTime.Parse(Request["selEndWarrantyTime"].ToString());
                string selUserManager = Request["selUserManager"] == null ? "" : Request["selUserManager"].ToString();

                string strJson;

                int totalCount;   //输出参数
                using (CYOADBEntities Entities = new CYOADBEntities())
                {
                    var linq = from a in Entities.ProInfo_Tab
                               select new ProInfoModel
                               {
                                   ProjectGuid = a.ProjectGuid,
                                   ProjectId = a.ProjectId,
                                   ProjectName = a.ProjectName,
                                   ProjectManager = a.ProjectManager,
                                   ProjectTel = a.ProjectTel,
                                   SignTime = a.SignTime,
                                   CompletionTime = a.CompletionTime,
                                   AcceptanceTime = a.AcceptanceTime,
                                   WarrantyTime = a.WarrantyTime,
                                   UserManager = a.UserManager,
                                   UserTel = a.UserTel,
                                   Describe = a.Describe,
                                   Address = a.Address,
                                   Longitude = a.Longitude,
                                   Latitude = a.Latitude,
                               };
                    if (!string.IsNullOrEmpty(selProjectName))
                    {
                        linq = linq.Where(i => i.ProjectName.Contains(selProjectName));
                    }
                    if (!string.IsNullOrEmpty(selProjectId))
                    {
                        linq = linq.Where(i => i.ProjectId.Contains(selProjectId));
                    }
                    if (selStartWarrantyTime != tmp && selEndWarrantyTime != tmp)
                    {
                        linq = linq.Where(a => a.WarrantyTime >= selStartWarrantyTime && a.WarrantyTime <= selEndWarrantyTime);
                    }
                    if (!string.IsNullOrEmpty(selUserManager))
                    {
                        linq = linq.Where(i => i.UserManager.Contains(selUserManager));
                    }
                    totalCount = linq.Count();
                    List<ProInfoModel> list = linq.OrderBy(i => i.SignTime).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                    JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                    strJson = jsonSerialize.Serialize(list);
                }
                var jsonResult = new { total = totalCount.ToString(), rows = strJson };
                return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
            }
            catch (Exception ee)
            {
                return Content("{\"total\": 0,\"rows\":''}");
            }
        }

        /// <summary>
        /// 根据ID删除项目信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DelProInfo()
        {
            string ProjectGuid = Request["ProjectGuid"];
            int Code = 0;
            string msg = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                ProInfo_Tab lmt = Entities.ProInfo_Tab.Where(i => i.ProjectGuid == ProjectGuid).FirstOrDefault();
                if (lmt != null)
                {
                    Entities.ProInfo_Tab.Add(lmt);
                    Entities.Entry<ProInfo_Tab>(lmt).State = System.Data.Entity.EntityState.Deleted;
                    Code = Entities.SaveChanges();
                }
                else
                {
                    Code = -1;
                    msg = "未查询到信息，无法删除";
                }
                if (Code > 0)
                {
                    new DocumentController().DelDocumentByID(lmt.ProjectId);
                    DelDevProRelation(lmt.ProjectId);
                    return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！" + msg + "\",\"success\":true}");
                }
            }

        }
        /// <summary>
        /// 删除项目是 删除设备出库的相关信息并把出库设备还原成未出库状态
        /// </summary>
        public void DelDevProRelation(string ProjectGuid)
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                List<DevProRelation_Tab> list = Entities.DevProRelation_Tab.Where(i => i.Code == ProjectGuid && i.CodeId == "1").ToList();
                if (list != null && list.Count > 0)
                {
                    foreach (DevProRelation_Tab DevProRelation in list)
                    {
                        Entities.DevProRelation_Tab.Add(DevProRelation);
                        Entities.Entry<DevProRelation_Tab>(DevProRelation).State = System.Data.Entity.EntityState.Deleted;

                        DevInfo_Tab DevInfoTab = Entities.DevInfo_Tab.Where(i => i.DeviceId == DevProRelation.DeviceId).FirstOrDefault();
                        if (DevInfoTab != null)
                        {
                            DevInfoTab.State = 0;
                            Entities.DevInfo_Tab.Add(DevInfoTab);
                            Entities.Entry<DevInfo_Tab>(DevInfoTab).State = System.Data.Entity.EntityState.Modified;

                            //获取设备的关系
                            DevTpRelation_Tab DevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == DevInfoTab.ID).FirstOrDefault();
                            string DevPath = "";
                            if (DevTpRelation != null)
                            {
                                DevPath = DevTpRelation.Path;
                            }
                            else
                            {
                                DevPath = DevInfoTab.ID + ",";
                            }
                            //获取当前设备下的所有子设备
                            List<DevTpRelation_Tab> DevTpRelationTabList = Entities.DevTpRelation_Tab.Where(i => i.Path.StartsWith(DevPath) && i.DeviceId != DevInfoTab.ID).ToList();
                            if (DevTpRelationTabList.Count > 0)
                            {
                                foreach (DevTpRelation_Tab dtrt in DevTpRelationTabList)
                                {
                                    DevInfo_Tab sonDevInfoTab = Entities.DevInfo_Tab.Where(i => i.ID == dtrt.DeviceId).FirstOrDefault();
                                    sonDevInfoTab.State = 0;
                                    Entities.DevInfo_Tab.Add(sonDevInfoTab);
                                    Entities.Entry<DevInfo_Tab>(sonDevInfoTab).State = System.Data.Entity.EntityState.Modified;
                                }
                            }
                        }
                    }
                   Entities.SaveChanges();
                }
            }
        }
    }
}
